package com.ys.utils.base.j2se;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.*;
import org.apache.commons.collections.CollectionUtils;

import java.io.File;
import java.io.InputStream;
import java.util.Date;

public class OssFileUtil {
	public static String DOMAIN = "https://aloss.tianbaoyunying.com/";
	public static String bucketName = "tbyy";

	/*
	 * Constructs a client instance with your account for accessing OSS
	 */
//	private static OSS ossClient;

	private static OSS init() {
		String endpoint = "http://oss-cn-qingdao.aliyuncs.com";
		String accessKeyId = "LTAI4GD6rezzzE2DFD292Uib";
		String accessKeySecret = "iOmzImNiTeZmbwgFfKoQkeeaoR5zaq";
		return new OSSClientBuilder().build(endpoint,accessKeyId,accessKeySecret);
	}

	/*
	 * Upload an object to your bucket
	 */
	public static void putFile(String path, File file){
		OSS ossClient = init();
		try{
			ossClient.putObject(new PutObjectRequest(bucketName, path, file));
		}catch (Throwable e){
			throw new RuntimeException(e);
		}finally {
			ossClient.shutdown();
		}
	}

	/*
	 * Upload an object to your bucket
	 * Set expiration time
	 */
	public static void putFile(String path, File file,int second){
		OSS ossClient = init();
		try{
			ObjectMetadata metadata = new ObjectMetadata();
			metadata.setExpirationTime(DateUtil.addSecond(new Date(),second));
			ossClient.putObject(new PutObjectRequest(bucketName, path, file, metadata));
		}catch (Throwable e){
			throw new RuntimeException(e);
		}finally {
			ossClient.shutdown();
		}
	}

	/*
	 * Upload an stream to your bucket
	 */
	public static void putStream(String path, InputStream input){
		OSS ossClient = init();
		try{
			ossClient.putObject(new PutObjectRequest(bucketName, path, input));
		}catch (Throwable e){
			throw new RuntimeException(e);
		}finally {
			ossClient.shutdown();
		}
	}

	/*
	 * Upload an stream to your bucket
	 * Set expiration time
	 */
	public static void putStream(String path, InputStream input,int second){
		OSS ossClient = init();
		try{
			ObjectMetadata metadata = new ObjectMetadata();
			metadata.setExpirationTime(DateUtil.addSecond(new Date(),second));
			ossClient.putObject(new PutObjectRequest(bucketName, path, input, metadata));
		}catch (Throwable e){
			throw new RuntimeException(e);
		}finally {
			ossClient.shutdown();
		}
	}

	/**
	 * 获取oss文件
	 * @param bucketName
	 * @param objectName
	 * @return
	 */
	public static OSSObject getObject(String bucketName, String objectName){
		OSS ossClient = init();
		try{
			return ossClient.getObject(bucketName,objectName);
		}catch (Throwable e){
			throw new RuntimeException(e);
		}finally {
			ossClient.shutdown();
		}
	}

	/**
	 * 查看oss上文件是否存在
	 * @param filePath
	 * @return
	 */
	public static String getObjectName(String filePath) {
		OSS ossClient = init();
		try{
			// 构造ListObjectsRequest请求
			ListObjectsRequest listObjectsRequest = new ListObjectsRequest(bucketName);
			//Delimiter 设置为 “/” 时，罗列该文件夹下的文件
			listObjectsRequest.setDelimiter("/");
			//Prefix 设为某个文件夹名，罗列以此 Prefix 开头的文件
			listObjectsRequest.setPrefix(filePath);
			//列举文件夹下所有文件
			ObjectListing listing = ossClient.listObjects(listObjectsRequest);
			if(CollectionUtils.isEmpty(listing.getObjectSummaries())){
				Logger.error("文件夹为空：" + filePath,null);
				return null;
			}
			//打印所有文件
			for (OSSObjectSummary os :listing.getObjectSummaries()) {
				Logger.info("文件：--{}",os.getKey());
				//结尾为“csv”即文件全路径
				if(os.getKey().endsWith("csv")){
					return os.getKey();
				}
			}
		}catch (OSSException e) {
			// OSS在查找不到某对象时，会抛出ErrorCode为“NoSuchKey”的OSSException，而不是返回null
			if (e.getErrorCode().contains("NoSuchKey")) {
				Logger.error("找不到文件夹：" + filePath,e);
			} else {
				Logger.error("OSS连接失败！,emsg:{}",e);
			}
			return null;
		}
		return null;
	}
}
